<?php

namespace App\Http\Controllers\Web\Maintain;

use App\Enum\enum_wechat;
use App\Http\Controllers\Api\ApiBaseController;
use App\Http\Controllers\Api\Login\UserController;
use App\Http\Format\FormatBase;
use App\Models\AdminWorkModel;
use App\Models\CityChinaModel;
use App\Models\MessageModel;
use App\Models\OpLogsModel;
use App\Models\OrderModel;
use App\Models\PayConfigModel;
use App\Models\PosterModel;
use App\Models\SearchLogModel;
use App\Models\ShareLogModel;
use App\Models\SysRoleModel;
use App\Models\SysUserModel;
use App\Models\SysUserRoleModel;
use App\Models\TableItemModel;
use App\Models\TableModel;
use App\Models\TagsModel;
use App\Models\TaskTagModel;
use App\Models\ToUserTaskModel;
use App\Models\UserModel;
use App\Models\UserPublicModel;
use App\Models\UserPublicSearchModel;
use App\Services\CurlBasiceService;
use App\Services\Web\TableService;
use App\Services\Web\TaskService;
use App\Services\Web\UserService;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class TaskController extends ApiBaseController
{

    /**
     * 总信息数据
     * @return object|null
     */
    public function task_static(Request $request): object
    {
        $params = $request->only(['start_time', 'end_time']);
        $params['start_time'] = !empty($params['start_time']) ? strtotime($params['start_time']) : strtotime(date("Y-m-d 00:00:00"));
        $params['end_time'] = !empty($params['end_time']) ? strtotime($params['end_time']) : strtotime(date("Y-m-d 23:59:59"));

        //今日信息总数
        $message_total = UserPublicModel::getCount([['created_at', '>=', strtotime(date("Y-m-d 00:00:00"))]]);

        //今日打赏总额
        $today_give_a_reward_total = OrderModel::getUserData([['created_at', '>=', strtotime(date("Y-m-d 00:00:00"))], ['status', '=', 1]], 'style', [1,5] );
        $today_give_a_reward_total = array_column($today_give_a_reward_total, 'money');
        $today_give_a_reward_total = array_sum($today_give_a_reward_total) / 100;

        //昨日打赏总额
        $yesterday_give_a_reward_total = OrderModel::getUserData([['created_at', '>=', (strtotime(date("Y-m-d 00:00:00")) - 86400) ], ['created_at', '<=', strtotime(date("Y-m-d 00:00:00"))], ['status', '=', 1]], 'style', [1,5] );
        $yesterday_give_a_reward_total = array_column($yesterday_give_a_reward_total, 'money');
        $yesterday_give_a_reward_total = array_sum($yesterday_give_a_reward_total) / 100;

        //近7天打赏总额
        $last_7_day_give_a_reward_total = OrderModel::getUserData([['created_at', '>=', (strtotime(date("Y-m-d 00:00:00")) - (86400*7))], ['status', '=', 1]], 'style', [1,5] );
        $last_7_day_give_a_reward_total = array_column($last_7_day_give_a_reward_total, 'money');
        $last_7_day_give_a_reward_total = array_sum($last_7_day_give_a_reward_total) / 100;

        //信息走势
        $where[] = ['created_at', '>=', $params['start_time'] ];
        $where[] = ['created_at', '<=', $params['end_time'] ];
        $result = UserPublicModel::getUserDataGroup($where);
        $result = array_column($result, null, 'created_date');
//        var_dump($result);die;

        $dateAll = $this->handleTimeDate($params['start_time'], $params['end_time']);
        $line_chart = [];
        foreach ($dateAll as $value){
            if (!empty($result[$value])){
                $line_chart[$value] = $result[$value]['count'];
            }else{
                $line_chart[$value] = 0;
            }
        }

        $info = [
            'message_total'=> $message_total,
            'today_give_a_reward_total'=> $today_give_a_reward_total,
            'yesterday_give_a_reward_total'=> $yesterday_give_a_reward_total,
            'last_7_day_give_a_reward_total'=> $last_7_day_give_a_reward_total,
            'line_chart'=>$line_chart
        ];

        return $this->codeSuccess($info);
    }

    public function handleTimeDate($start, $end){
        $res = [];
        $end = date("Y-m-d 23:59:59", $end);
        $end = strtotime($end);
        for ($i = $start; $i < $end; $i+=86400){
            $res[] = $i;
        }
        return $res;
    }

    /**
     * 任务列表（时间，分类，上下午，信息编号，手机号，微信号，发布地区（省市区））
     * @return object|null
     */
    public function task_list_maintain(Request $request): object
    {
        $params = $request->only(['day_type', 'time_type', 'cat_1', 'no', 'mobile', 'number', 'area', 'city', 'address', 'limit', 'page'
         , 'sys_user_id', 'style', 'content_vip', 'is_order_plain_end_time']);

        //添加筛选条件
        $where = TaskService::getInstance()->handleTask($params);
        $where[] = ['info_user_public.admin_id', '=', adminInfo('id')];


        $list = UserPublicModel::getPageJoinUser($where, $params['limit'] ?? 15
            , 'info_user_public.*, info_user.id as user_id, info_user.nickname, info_user.number'
        , '', [], [], [], [0]);

        foreach ($list['data'] as &$value){
            //分类
            if (!empty($value['cat_2_msg'][0]['name'])){
                $value['cat_2_msg'] = $value['cat_2_msg'][0]['name'];

            }else{
                $value['cat_2_msg'] = '';

            }

            if (!empty($value['cat_1_msg'][0]['que_id'])){
                $value['que_id'] = $value['cat_1_msg'][0]['que_id'];

            }else{
                $value['que_id'] = 0;

            }

            //存在 que_real_id ，取que_real_id。没有que_real_id调用接口
            if(empty($value['que_real_id']) && !empty($value['que_id'])){
                //http://api.gz.muke.bailingkeji.com/admin/questionnaire/clone/list
                // alias que_id
                // que_type 2
                // page 1
                // limit 20
                $result_que = CurlBasiceService::getInstance()->httpPost('http://api.customer.form.bailingkeji.com/admin/questionnaire/clone/list'
                    , json_encode([
                        'alias'=> $value['que_id'],
                        'que_type'=> 2,
                        'page'=> 1,
                        'limit'=> 20,
                    ]), []);

                if (!empty($result_que['data']['list'][0]['id'])){
                    $value['que_id'] = $result_que['data']['list'][0]['id'];
                }
            }

            if (!empty($value['cat_1_msg'][0]['name'])){
                $value['cat_1_msg'] = $value['cat_1_msg'][0]['name'];

            }else{
                $value['cat_1_msg'] = '';

            }

            //维护人id
            $value['admin_nickname'] = '';
            if (!empty($value['admin_msg'][0]['nickname'])){
                $value['admin_nickname'] = $value['admin_msg'][0]['nickname'];
            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }

            //用户手机号
            $value['user_mobile'] = '';
            if (!empty($value['users'][0]['mobile'])){
                $value['user_mobile'] = $value['users'][0]['mobile'];
            }

            //结束时间
            $value['done_time'] = date('Y-m-d H:i:s', $value['done_time']);

            //创建时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            //操作时间
            $value['op_time'] = date('Y-m-d H:i:s', $value['op_time']);

            $value['content'] = '';

            unset($value['admin_msg']);
        }

        //总条数获取 $list['handle_total']
        $where[] = ['info_user_public.status', '=', 1];
        $where[] = ['info_user_public.done_time', '>', (time() - (86400*3))];
        $list['handle_total'] = UserPublicModel::getPageJoinUserCount($where, $params['limit'] ?? 15
            , 'info_user_public.*, info_user.id as user_id, info_user.nickname, info_user.number');

        return $this->codeSuccess(FormatBase::listData($list));
    }

    /**
     * 任务列表（时间，分类，上下午，信息编号，手机号，微信号，发布地区（省市区））
     * @return object|null
     */
    public function task_list(Request $request): object
    {
        $params = $request->only(['day_type', 'time_type', 'cat_1', 'no', 'mobile', 'number', 'area', 'city', 'address', 'limit', 'page'
            , 'sys_user_id', 'style', 'content_vip', 'is_order_plain_end_time']);

        if(empty($params['day_type'])){
            $params['day_type'] = 1;
        }

        //添加筛选条件
        $where = TaskService::getInstance()->handleTask($params);

        //获取部门的所有人员
//        $role = SysUserRoleModel::getSing(['uid'=> adminInfo('id')]);
//        if(!empty($role['role_id'])){
//            //获取部门的所有用户
//            $role = SysUserRoleModel::getDataOne(['role_id'=> $role['role_id']]);
//            $role = array_column($role, 'uid');
//        }

        //排序
        $order = [];
        if(!empty($params['is_order_plain_end_time'])){
            $order = ['plain_end_time', $params['is_order_plain_end_time'] == 1 ? 'asc' : 'desc'];
        }

        //超管展示所有数据
        if (adminInfo('id') <> 1){
            $user_info = SysUserModel::getSingle(['id'=> adminInfo('id')]);
            $where[] = ['info_user_public.area', '=', $user_info['area_province_id']];
            $where[] = ['info_user_public.city', '=', $user_info['area_city_id']];
            $where[] = ['info_user_public.address', '=', $user_info['area_district_id']];
        }

        if (isset($params['cat_1']) && $params['cat_1'] == 0){
            $list = UserPublicModel::getPageJoinUser($where, $params['limit'] ?? 15
                , 'info_user_public.*, info_user.id as user_id, info_user.nickname, info_user.number'
                , '', [], $order, $params, []);
        }else{
            $list = UserPublicModel::getPageJoinUser($where, $params['limit'] ?? 15
                , 'info_user_public.*, info_user.id as user_id, info_user.nickname, info_user.number'
                , '', [], $order, $params, [], [4,5,6]);
        }

        foreach ($list['data'] as &$value){
            //分类
            if (!empty($value['cat_2_msg'][0]['name'])){
                $value['cat_2_msg'] = $value['cat_2_msg'][0]['name'];

            }else{
                $value['cat_2_msg'] = '';

            }

            if (!empty($value['cat_1_msg'][0]['que_id'])){
                $value['que_id'] = $value['cat_1_msg'][0]['que_id'];

            }else{
                $value['que_id'] = 0;

            }

            if (!empty($value['cat_1_msg'][0]['name'])){
                $value['cat_1_msg'] = $value['cat_1_msg'][0]['name'];

            }else{
                $value['cat_1_msg'] = '';

            }

            //维护人id
            $value['admin_nickname'] = '';
            if (!empty($value['admin_msg'][0]['nickname'])){
                $value['admin_nickname'] = $value['admin_msg'][0]['nickname'];
            }

            //用户手机号
            $value['user_mobile'] = '';
            if (!empty($value['users'][0]['mobile'])){
                $value['user_mobile'] = $value['users'][0]['mobile'];
            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }


            //结束时间
            $value['done_time'] = date('Y-m-d H:i:s', $value['done_time']);

            //创建时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            //操作时间
            $value['op_time'] = date('Y-m-d H:i:s', $value['op_time']);

            $value['content'] = TaskService::getInstance()->handle_rpc_info($value['id']);

//            if (!empty($value['content'])){
//                $value['content'] = (new UserController($request))->handlePreview($value['table_id'], $value['content']);
//            }

            unset($value['admin_msg']);
        }

        if (!(isset($params['cat_1']) && $params['cat_1'] == 0)){
            //总条数获取 $list['handle_total']
            $where[] = ['info_user_public.status', '=', 6];
            $list['handle_total'] = UserPublicModel::getPageJoinUserCount($where, $params['limit'] ?? 15
                , 'info_user_public.*, info_user.id as user_id, info_user.nickname, info_user.number'
                , '', [], $order, $params, []);
        }

        return $this->codeSuccess(FormatBase::listData($list));
    }

    public function task_list_search(Request $request): object
    {
        $params = $request->only(['day_type', 'time_type', 'cat_1', 'no', 'mobile', 'number', 'area', 'city', 'address', 'limit', 'page'
            , 'sys_user_id', 'style', 'content_vip', 'is_order_plain_end_time']);

        if(empty($params['day_type'])){
            $params['day_type'] = 1;
        }

        //添加筛选条件
        $where = TaskService::getInstance()->handleTaskSearch($params);

//        //获取部门的所有人员
//        $role = SysUserRoleModel::getSing(['uid'=> adminInfo('id')]);
//        if(!empty($role['role_id'])){
//            //获取部门的所有用户
//            $role = SysUserRoleModel::getDataOne(['role_id'=> $role['role_id']]);
//            $role = array_column($role, 'uid');
//        }

        //排序
        $order = [];
        if(!empty($params['is_order_plain_end_time'])){
            $order = ['plain_end_time', $params['is_order_plain_end_time'] == 1 ? 'asc' : 'desc'];
        }

        //超管展示所有数据
        if (adminInfo('id') <> 1){
            $user_info = SysUserModel::getSingle(['id'=> adminInfo('id')]);
            $where[] = ['info_user_public_search.area', '=', $user_info['area_province_id']];
            $where[] = ['info_user_public_search.city', '=', $user_info['area_city_id']];
            $where[] = ['info_user_public_search.address', '=', $user_info['area_district_id']];
        }

        $list = UserPublicSearchModel::getPageJoinUser($where, $params['limit'] ?? 15
            , 'info_user_public_search.*, info_user.id as user_id, info_user.nickname, info_user.number'
            , '', [], $order, $params, [0, 9]);

        foreach ($list['data'] as &$value){
            //分类
            if (!empty($value['cat_2_msg'][0]['name'])){
                $value['cat_2_msg'] = $value['cat_2_msg'][0]['name'];

            }else{
                $value['cat_2_msg'] = '';

            }

            if (!empty($value['cat_1_msg'][0]['name'])){
                $value['cat_1_msg'] = $value['cat_1_msg'][0]['name'];

            }else{
                $value['cat_1_msg'] = '';

            }

            //维护人id
            $value['admin_nickname'] = '';
            if (!empty($value['admin_msg'][0]['nickname'])){
                $value['admin_nickname'] = $value['admin_msg'][0]['nickname'];
            }

            //用户手机号
            $value['user_mobile'] = '';
            if (!empty($value['users'][0]['mobile'])){
                $value['user_mobile'] = $value['users'][0]['mobile'];
            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }


            //结束时间
            $value['done_time'] = date('Y-m-d H:i:s', $value['done_time']);

            //创建时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            //操作时间
            $value['op_time'] = date('Y-m-d H:i:s', $value['op_time']);

            $value['one_money'] = '';
            //用于计算剩余点数
            $one_money = 0;
            //单价
            if (!empty($value['seach_page'])){
                switch ($value['seach_page']){
                    case 1:
                        $value['one_money'] = '1.00/PV';
                        $one_money = 1;
                        break;
                    case 2:
                        $value['one_money'] = '0.80/PV';
                        $one_money = 0.8;

                        break;
                    case 3:
                        $value['one_money'] = '0.50/PV';
                        $one_money = 0.5;

                        break;
                }
            }

            $value['use_seach_count'] = 0;
            if (!empty($value['search_log'])){
                $value['use_seach_count'] = count($value['search_log']);
            }

            //剩余点数
            $value['let_money'] = '';
            if (!empty($value['seach_money']) && !empty($one_money)){
                $value['let_money'] = $value['seach_money'] - ($value['use_seach_count'] * $one_money);
            }

            $value['content'] = json_decode($value['content'], true);
            if (!empty($value['content'])){
                $value['content'] = (new UserController($request))->handlePreview($value['table_id'], $value['content']);
            }

            $value['content'] = TaskService::getInstance()->handle_rpc_info($value['id'], 1);

            unset($value['admin_msg']);
        }

        //总条数获取 $list['handle_total']
        $where[] = ['info_user_public_search.status', '=', 1];
        $list['handle_total'] = UserPublicSearchModel::getPageJoinUserCount($where, $params['limit'] ?? 15
            , 'info_user_public_search.*, info_user.id as user_id, info_user.nickname, info_user.number'
            , '', [], $order, $params, []);
        return $this->codeSuccess(FormatBase::listData($list));
    }

    public function vip_create_task(Request $request): object
    {
        $params = $request->only(['id', 'area', 'city', 'address', 'admin_id', 'content_vip']);

        $bool = $this->handleIsNull($params, ['id', 'area', 'city', 'address', 'admin_id', 'content_vip']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        if (!empty($params['id'])){
            //修改
            $params['plain_end_time'] = time() + (86400 * 3);
            $params['created_at'] = time();
            $params['done_time'] = time() + (86400 * 3);
            $params['handle_time'] = date('H', time()) >= 18 ? (time() + (86400 / 2)) : time();
            $params['updated_at'] = time();
            $params['op_time'] = time();

            UserPublicModel::updateSingle(['id'=> $params['id']], $params);

            //加日志
            $this->createOp(1, $params['id']);
        }


        return $this->codeSuccess();

    }

    /**
     * 任务处理：通过并移交，通过，驳回，转移（上下午转），取消（加日志）
     * @param Request $request
     * @return object
     */
    public function task_handle(Request $request): object
    {
        $params = $request->only(['id', 'style', 'keyword']);

        //查询是否存在
        $publicInfo = UserPublicModel::getSingle(['id'=> $params['id']]);
        if (empty($publicInfo)){
            return $this->codeError([], 1011, '数据不存在');

        }
        $update = ['status'=> $params['style'], 'updated_at'=>time(), 'op_time'=>time()];
        //处理
        switch ($params['style']){
            case 6:
                //通过并移交
                $update['check_status'] = time();
                $update['status'] = 6;

                break;
            case 5:
                //通过
                $update['status'] = 5;
                $update['done_time'] = time();

                break;
            case 4:
                //驳回
                $update['status'] = 4;

                break;
            case 3:
                //待删除
                $update['status'] = 1000;
                $update['deleted_keyword'] = $params['keyword'] ?? '';
                $update['handle_time'] = date('H', time()) >= 18 ? (time() + (86400 / 2)) : time();

                break;
            case 999:
                //转移（上下午转）
                $handle_time = !empty($publicInfo['handle_time']) ? $publicInfo['handle_time'] : time();
                $handle_time = $handle_time + (86400/2);
                UserPublicModel::updateSingle(['id'=> $params['id']], ['handle_time'=>$handle_time, 'updated_at'=>time(), 'op_time'=>time()]);
                break;
            case 2:
                //取消

                break;
            case 1000:
                $update['status'] = 3;

                break;
        }

        //修改
        if (!empty($params['style']) && in_array($params['style'], [2,3,4,5,6,1000])){
            UserPublicModel::updateSingle(['id'=> $params['id']], $update);
        }

        //41引流、42匹配、43搜索、44完成
        if ($params['style'] == 43){
            $this->createOp(43, $params['id']);
            $this->createOp(44, $params['id']);
        }
        //日志
        $this->createOp($params['style'], $params['id']);


        return $this->codeSuccess();

    }

    /**
     * 任务处理：通过并移交，通过，驳回，转移（上下午转），取消（加日志）
     * @param Request $request
     * @return object
     */
    public function task_handle_search(Request $request): object
    {
        $params = $request->only(['id', 'style', 'keyword', 'seach_three_id']);

        //查询是否存在
        $publicInfo = UserPublicSearchModel::getSingle(['id'=> $params['id']]);
        if (empty($publicInfo)){
            return $this->codeError([], 1011, '数据不存在');

        }
        $update = ['status'=> $params['style'], 'updated_at'=>time(), 'op_time'=>time()];
        //处理
        switch ($params['style']){
            case 6:
                //通过并移交
                $update['style'] = 6;

                break;
            case 5:
                //通过
                $update['style'] = 5;
                $update['done_time'] = time();
                $update['seach_three_id'] = $params['seach_three_id'] ?? '';
                switch ($params['seach_three_id']){
                    case 1:
                        $update['seach_three_type'] = '未知';
                        break;
                    default:
                        $update['seach_three_type'] = '未知';
                        break;
                }

                //修改订单三方id
                if (!empty($params['seach_three_id'])){
                 $order = OrderModel::getSingle(['public_id'=> $params['id'], 'style'=> 7]);
                 if (!empty($order['id'])){
                  OrderModel::updateSingle(['id'=> $order['id']],[
                      'three_id'=> $params['seach_three_id']
                  ]);
                 }
                }

                break;
            case 4:
                //驳回
                $update['style'] = 4;

                break;
            case 3:
                //删除
                $update['deleted_keyword'] = $params['keyword'] ?? '';

                break;
            case 999:
                //转移（上下午转）
                $handle_time = !empty($publicInfo['handle_time']) ? $publicInfo['handle_time'] : time();
                $handle_time = $handle_time + (86400/2);
                UserPublicSearchModel::updateSingle(['id'=> $params['id']], ['handle_time'=>$handle_time, 'updated_at'=>time(), 'op_time'=>time()]);
                break;
            case 2:
                //取消

                break;
        }

        //修改
        if (!empty($params['style']) && in_array($params['style'], [2,3,4,5,6])){
            UserPublicSearchModel::updateSingle(['id'=> $params['id']], $update);
        }

        //日志
        $this->createOp($params['style'], $params['id'], '', '', 1);

        return $this->codeSuccess();

    }

    /**
     * 任务修改（加日志）
     * @param Request $request
     * @return object
     */
    public function task_update(Request $request): object
    {
        $params = $request->only(['id', 'content', 'area_json', 'tag_json']);

        $bool = $this->handleIsNull($params, ['id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        if (empty($params['content']) && empty($params['area_json']) && empty($params['tag_json'])){
            return $this->codeError([], 1011, '无修改内容');
        }

        if (!empty($params['content'])){
            $params['content'] = json_encode($params['content']);
        }

        if (!empty($params['area_json'])){
            $params['area_json'] = json_encode($params['area_json']);
        }

        if (!empty($params['tag_json'])){
            $params['tag_json'] = json_encode($params['tag_json']);
        }

        if (!empty($params['id'])){
            //修改
            $params['updated_at'] = time();
            $params['op_time'] = time();

            UserPublicModel::updateSingle(['id'=> $params['id']], $params);

            //加日志
            $this->createOp(998, $params['id']);
        }


        return $this->codeSuccess();
    }


    /**
     * 添加任务标签
     * @param Request $request
     * @return object
     */
    public function task_tag(Request $request): object
    {
        $params = $request->only(['id', 'tag']);

        //添加标签
        TaskTagModel::insertSingle([
            'tag'=> $params['tag'],
            'task_id'=> $params['id'],
        ]);

        //加日志
        $this->createOp(997, $params['id'], $params['tag'] ?? '');

        return $this->codeSuccess();

    }

    public function task_tag_list_maintain(Request $request): object
    {
        $params = $request->only(['day_type']);
        if (empty($params['day_type'])){
            $params['day_type'] = 1;
        }

        $list = TagsModel::getUserData(['parent_id'=>0], '', [], $params['day_type'] ?? 1);

        foreach ($list as &$value){
            $value['count'] = count($value['user_public']);
            $value['num'] = count($value['user_public']);
            unset($value['user_public']);
        }

        return $this->codeSuccess($list);

    }

    public function task_tag_list(Request $request): object
    {
        $params = $request->only(['day_type']);
        if (empty($params['day_type'])){
            $params['day_type'] = 1;
        }

        $user_info = SysUserModel::getSingle(['id'=> adminInfo('id')]);

        $list = TagsModel::getUserDataPublish(['parent_id'=>0], '', [], $params['day_type'] ?? 1, '*', $user_info);

        foreach ($list as &$value){
            $value['count'] = count($value['user_public_1']);
            $value['num'] = count($value['user_public_1']);
            unset($value['user_public_1']);
        }

        return $this->codeSuccess($list);

    }

    public function task_tag_list_search(Request $request): object
    {
        $params = $request->only(['day_type']);
        if (empty($params['day_type'])){
            $params['day_type'] = 1;
        }

        $user_info = SysUserModel::getSingle(['id'=> adminInfo('id')]);

        $list = TagsModel::getUserDataSearch(['parent_id'=>0], '', [], $params['day_type'] ?? 1, '*', $user_info);

        foreach ($list as &$value){
            $value['count'] = count($value['user_public_search_1']);
            $value['num'] = count($value['user_public_search_1']);
            unset($value['user_public_search_1']);
        }

        return $this->codeSuccess($list);
    }

    public function task_match(Request $request): object
    {
        $params = $request->only(['city_id','tag','task_id']);
        $bool = $this->handleIsNull($params, ['city_id','tag','task_id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        //添加日志 42匹配
        $this->createOp(42, $params['task_id']);

        return $this->codeSuccess([]);
    }

    public function tag_list(Request $request): object
    {
        $params = $request->only(['task_id']);
        $bool = $this->handleIsNull($params, ['task_id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        $res = UserPublicModel::getSingle(['id'=> $params['task_id']]);

        $data = [];

        if (!empty($res['tag_json'])){
            $res['tag_json'] = json_decode($res['tag_json'], true);
            foreach ($res['tag_json'] as $value){
                unset($temp);
                $temp['tag'] = $value;
                $data[] = $temp;
            }
        }

        return $this->codeSuccess($data);
    }

    /**
     * 回访列表
     * @return object|null
     */
    public function visit_list(Request $request): object
    {
        $params = $request->only(['visit_status', 'cat_1', 'no', 'mobile', 'number', 'area', 'city', 'address', 'limit', 'page']);

        //添加筛选条件
        $where = TaskService::getInstance()->handleTask($params, 2);

        //排序
        $order = [];
        if(!empty($params['is_order_plain_end_time'])){
            $order = ['plain_end_time', $params['is_order_plain_end_time'] == 1 ? 'asc' : 'desc'];
        }

        //完成时间超过3天的
        if(!empty($params['visit_status'])){
            if ($params['visit_status'] == 1){
                //待回访
                $where[] = ['info_user_public.done_time' ,'<', (time() - (86400 * 3))];
                $where[] = ['info_user_public.done_time' ,'>', (time() - (86400 * 6))];
                $where[] = ['info_user_public.visit_time' ,'=', 0];

            }else if($params['visit_status'] == 3){
                $where[] = ['info_user_public.done_time' ,'<', (time() - (86400 * 6))];
                $where[] = ['info_user_public.visit_time' ,'=', 0];

            }
        }
        $where[] = ['info_user_public.status', '=', 5];

        $list = UserPublicModel::getPageJoinUser($where, $params['limit'] ?? 15, 'info_user_public.*, info_user.nickname, info_user.number',
        '', [], $order);

        foreach ($list['data'] as &$value){
            //分类
            if (!empty($value['cat_1_msg'][0]['name'])){
                $value['cat_1_msg'] = $value['cat_1_msg'][0]['name'];

            }else{
                $value['cat_1_msg'] = '';

            }

            if (!empty($value['cat_2_msg'][0]['name'])){
                $value['cat_2_msg'] = $value['cat_2_msg'][0]['name'];

            }else{
                $value['cat_2_msg'] = '';

            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }

            //超时天数
            $value['visit_day'] = '--';
            if (!empty($value['visit_created_at'])){
                $visit_time = !empty($value['visit_time']) ? $value['visit_time'] : time();
                $value['visit_day'] = (($visit_time - $value['visit_created_at']) / 3600) > 72 ? ceil((ceil(($visit_time - $value['visit_created_at']) / 3600) - 72)/24) : 0;
            }

            //结束时间
            $value['done_time'] = date('Y-m-d H:i:s', $value['done_time']);

            //创建时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);

            //操作时间
            $value['op_time'] = date('Y-m-d H:i:s', $value['op_time']);

            $value['content'] = json_decode($value['content'], true);
        }

        return $this->codeSuccess(FormatBase::listData($list));
    }

    /**
     * 操作：1重新发布到后台信息管理（加日志）,2超时处理, 3超时移交, 4用户维护, 5超时回访, 6催单处理, 7禁用申请  8禁用用户，9启用用户，10激活移交，11激活处理 到工单申请（加日志）
     * @return void
     */
    public function visit_handle(Request $request): object
    {
        $params = $request->only(['id', 'style']);
        $style = 0;
        switch ($params['style']){
            case 1:
                $style = 996;
                UserPublicModel::updateSingle(['id'=> $params['id']], ['visit_status'=> 1, 'status'=> 1, 'updated_at'=> time(), 'op_time'=>time(), 'handle_time'=>time(), 'plain_end_time'=>(time() + (86400 * 3)), 'done_time'=>0, 'visit_time'=>0, 'visit_appraise'=>'', 'visit_score'=>0]);

                break;
            case 2:
                $style = 995;

                break;
            case 3:
                $style = 994;

                break;
            case 4:
                $style = 993;

                break;
            case 5:
                $style = 992;

                break;
            case 6:
                $style = 991;

                break;
            case 7:
                $style = 990;

                break;

            case 8:
                $style = 986;

                break;

            case 9:
                $style = 985;

                break;

            case 10:
                $style = 984;

                break;

            case 11:
                $style = 983;

                break;
            case 20:
                $style = 982;
                UserPublicModel::updateSingle(['id'=> $params['id']], ['visit_status'=> 1, 'updated_at'=> time(), 'op_time'=>time(), 'done_time'=>time(), 'visit_time'=>0, 'visit_appraise'=>'', 'visit_score'=>0]);

                break;
        }

        if (!empty($params['style'])){
            if ($params['style'] <> 1){
                //加工单
                AdminWorkModel::insertSingle([
                    'style'=> $params['style'],
                    'task_id'=> $params['id'],
                    'created_at'=> time(),
                ]);
            }

            //加日志
            $this->createOp($style, $params['id']);
        }

        return $this->codeSuccess();
    }

    /**
     * 工单列表
     * @return object|null
     */
    public function work_list(Request $request): object
    {
        $params = $request->only(['style', 'status', 'no', 'mobile', 'number', 'area', 'city', 'address', 'limit', 'page']);

        //添加筛选条件
        $where = TaskService::getInstance()->handleTask($params);

        $list = AdminWorkModel::getPageJoinUser($where, $params['limit'] ?? 15, 'info_user_public.*, info_user.nickname, info_user.number, info_admin_work.style as work_style, info_admin_work.created_at as work_created_at, info_admin_work.status as work_status');

        foreach ($list['data'] as &$value){
            //分类
            if (!empty($value['cat_2_msg'][0]['name'])){
                $value['cat_2_msg'] = $value['cat_2_msg'][0]['name'];

            }else{
                $value['cat_2_msg'] = '';

            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }


            //结束时间
            $value['done_time'] = date('Y-m-d H:i:s', $value['done_time']);

            //创建时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
            $value['work_created_at'] = date('Y-m-d H:i:s', $value['work_created_at']);

            //操作时间
            $value['op_time'] = date('Y-m-d H:i:s', $value['op_time']);

            $value['content'] = json_decode($value['content'], true);
        }

        return $this->codeSuccess(FormatBase::listData($list));
    }

    /**
     * 操作：取消，通过，驳回（加日志）
     * @param Request $request
     * @return object
     */
    public function work_handle(Request $request): object
    {
        $params = $request->only(['id', 'style']);

        $style = 0;
        switch ($params['style']){
            case 4:
                //取消
                $style = 989;
                break;

            case 5:
                //通过 todo 事件后续修改
                $style = 988;

                break;

            case 2:
                //驳回
                $style = 987;

                break;

        }

        //修改
        AdminWorkModel::updateSingle(['id'=> $params['id']], ['status'=> $params['style']]);

        //日志
        $this->createOp($style, $params['id']);
        return $this->codeSuccess();

    }

    /**
     * 信息列表
     * @return object|null
     */
    public function data_list(Request $request): object
    {
        $params = $request->only(['style', 'cat_1', 'mobile', 'number', 'area', 'city', 'address', 'limit', 'page'
            , 'admin_id', 'is_pay', 'created_at_start', 'created_at_end', 'no', 'is_order_plain_end_time']);

        //添加筛选条件
        $where = TaskService::getInstance()->handleData($params);

        //排序
        $order = [];
        if(!empty($params['is_order_plain_end_time'])){
            $order = ['plain_end_time', $params['is_order_plain_end_time'] == 1 ? 'asc' : 'desc'];
        }

        $list = UserPublicModel::getPageJoinUser($where, $params['limit'] ?? 15, 'info_user_public.*, info_user.nickname, info_user.number',
        '', [], $order, $params, [1000]);

        foreach ($list['data'] as &$value){
            //分类
            if (!empty($value['cat_1_msg'][0]['name'])){
                $value['cat_1_msg'] = $value['cat_1_msg'][0]['name'];

            }else{
                $value['cat_1_msg'] = '';

            }

            if (!empty($value['cat_2_msg'][0]['name'])){
                $value['cat_2_msg'] = $value['cat_2_msg'][0]['name'];

            }else{
                $value['cat_2_msg'] = '';

            }

            //维护人id
            $value['admin_nickname'] = '';
            if (!empty($value['admin_msg'][0]['nickname'])){
                $value['admin_nickname'] = $value['admin_msg'][0]['nickname'];
            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }


            //结束时间
            $value['done_time'] = date('Y-m-d H:i:s', $value['done_time']);

            //创建时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
            $value['updated_at'] = date('Y-m-d H:i:s', $value['updated_at']);

            //操作时间
            $value['op_time'] = date('Y-m-d H:i:s', $value['op_time']);

            //超时天数
            $value['visit_day'] = '--';
            if (!empty($value['visit_created_at'])){
                $visit_time = !empty($value['visit_time']) ? $value['visit_time'] : time();
                $value['visit_day'] = (($visit_time - $value['visit_created_at']) / 3600) > 72 ? ceil((ceil(($visit_time - $value['visit_created_at']) / 3600) - 72)/24) : 0;
            }

            $value['content'] = json_decode($value['content'], true);
            if (!empty($value['content'])){
                $value['content'] = (new UserController($request))->handlePreview($value['table_id'], $value['content']);
            }

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }

            unset($value['admin_msg'],$value['area_msg'],$value['city_msg'],$value['address_msg']);
        }

        return $this->codeSuccess(FormatBase::listData($list));
    }

    public function task_logs(Request $request): object
    {
        $params = $request->only(['id']);

        $list = OpLogsModel::getUserData(['task_id'=> $params['id']]);

        foreach ($list as &$value){
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
        }
        return $this->codeSuccess($list);

    }

    public function task_list_static(Request $request): object
    {
        $once_sum = UserPublicModel::getCount(['admin_id'=> adminInfo('id')]);
        $once_handle = UserPublicModel::getCount(['admin_id'=> adminInfo('id'), 'status'=> 6]);
        $once_no_handle = UserPublicModel::getCount(['admin_id'=> adminInfo('id'), 'status'=> 1]);
        $once_await = UserPublicModel::getCount(['admin_id'=> adminInfo('id'), 'status'=> 8]);

        //获取这个用户的部门
        $user_depart = SysUserRoleModel::getDataOne(['uid'=> adminInfo('id')]);
        $departs = array_column($user_depart, 'role_id');
        $depart_user = SysUserRoleModel::getDataOne([], 'role_id', $departs);
        $depart_user = array_column($depart_user, 'uid');

        $depart_sum = UserPublicModel::getCount([], 'admin_id', $depart_user);
        $depart_handle = UserPublicModel::getCount(['status'=> 6], 'admin_id', $depart_user);
        $depart_no_handle = UserPublicModel::getCount(['status'=> 1], 'admin_id', $depart_user);
        $depart_await = UserPublicModel::getCount(['status'=> 8], 'admin_id', $depart_user);

        $data = [
            'once_sum'=>$once_sum,
            'once_handle'=>$once_handle,
            'once_no_handle'=>$once_no_handle,
            'once_await'=>$once_await,
            'whole_sum'=>$depart_sum,
            'whole_handle'=>$depart_handle,
            'whole_no_handle'=>$depart_no_handle,
            'whole_await'=>$depart_await,
        ];
        return $this->codeSuccess($data);

    }

    //task_list_static_maintain
    public function task_list_static_maintain(Request $request): object
    {
        $once_sum = UserPublicModel::getCount(['admin_id'=> adminInfo('id')]);
        $once_handle = UserPublicModel::getCount(['admin_id'=> adminInfo('id'), 'status'=> 6]);
        $once_no_handle = UserPublicModel::getCount(['admin_id'=> adminInfo('id'), 'status'=> 1]);
        $once_await = UserPublicModel::getCount(['admin_id'=> adminInfo('id'), 'status'=> 8]);

        //超时回访
        $gone_await = UserPublicModel::getCount(['admin_id'=> adminInfo('id'), 'visit_status'=> 3]);

        //工单申请（条）
        $work_order = UserPublicModel::getCount(['admin_id'=> adminInfo('id'), 'status'=> 3]);

        $data = [
            'once_sum'=>$once_sum,
            'once_handle'=>$once_handle,
            'once_no_handle'=>$once_no_handle,
            'once_await'=>$once_await,
            'gone_await'=>$gone_await,
            'work_order'=>$work_order,
        ];
        return $this->codeSuccess($data);

    }

    public function pay_config_list(Request $request): object
    {
        $params = $request->only([]);
        $data = PayConfigModel::getUserData();

        return $this->codeSuccess($data);

    }

    public function pay_config_edit(Request $request): object
    {
        $params = $request->only(['id', 'num', 'msg']);

        $bool = $this->handleIsNull($params, ['id', 'num', 'msg']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        $id = $params['id'];
        unset($params['id']);

        PayConfigModel::updateSingle(['id'=> $id], $params);
        return $this->codeSuccess();
    }

    public function pay_config_edit_status(Request $request): object
    {
        $params = $request->only(['id', 'status']);

        $bool = $this->handleIsNull($params, ['id', 'status']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        $id = $params['id'];
        unset($params['id']);

        PayConfigModel::updateSingle(['id'=> $id], $params);
        return $this->codeSuccess();
    }

    public function create_visit_log(Request $request): object
    {
        $params = $request->only(['id', 'visit_score', 'visit_appraise']);

        $bool = $this->handleIsNull($params, ['id', 'visit_score', 'visit_appraise']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');

        }

        //添加回访记录， 回访时间
        UserPublicModel::updateSingle(['id'=> $params['id']], [
            'visit_score'=> $params['visit_score'],
            'visit_appraise'=> $params['visit_appraise'],
            'visit_time'=> time(),
        ]);

        return $this->codeSuccess();
    }


    /**
     * 任务详情页
     * @return object|null
     */
    public function task_detail(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])) {
            return $this->codeError([], 1011, '参数错误');

        }

        //获取任务的表单id
        $userPublic = UserPublicModel::getSingle(['id'=> $params['id']]);
        if (empty($userPublic['table_id'])){
            return $this->codeError([], 1011, '任务不存在');

        }

        //任务 content
        $task_content = $userPublic['content'];
        $task_content = json_decode($task_content, true);
        $task_content_string = array_column($task_content, null, 'id');

        //任务地点 area_json
        $task_area_json = $userPublic['area_json'];
        $task_area_json = json_decode($task_area_json, true);

        //任务标签 tag_json
        $task_tag_json = $userPublic['tag_json'];
        $task_tag_json = json_decode($task_tag_json, true);

        //获取表单item
        $where[] = ['id', '=', $userPublic['table_id']];
        $info = TableModel::getUserOne($where);

        if (empty($info)){
            return $this->codeError([], 1011, '表单数据不存在');

        }

        $info['content_insert'] = json_decode($info['content_insert'], true);
        if (empty($info['content_insert'])){
            return $this->codeSuccess();

        }

        //查询content_insert所有值
        $ids = [];
        foreach ($info['content_insert'] as $value){
            if (is_array($value)){
                foreach ($value as $vs){
                    $ids[] = $vs;
                }
            }else{
                $ids[] = $value;
            }
        }

        //查询
        $list = TableItemModel::getUserData([], 'id', $ids);
        //id赋值到key上
        $list = array_column($list, null, 'id');

        //获取模板
        $tmp = enum_wechat::TEMP;
        $infoMsg = $tmp[$info['msg']];

        //根据title换参数
        foreach ($info['content_insert'] as $keys => $value){
            $artTemp = '--';
            if (!empty($task_content_string[$value]['content'])){
                $artTemp = $task_content_string[$value]['content'];
            }

            $infoMsg = preg_replace('/TITLE/', $artTemp ?? '', $infoMsg, 1);
        }

        // item_arr 任务详情
        $item_arr = [];
        $item_content = $info['content'];
        if (!empty($item_content)){
            $item_content = json_decode($item_content, true);
            $item_list = TableItemModel::getUserData([], 'id', $item_content);
            foreach ($item_list as &$vs_item){
                $vs_item['value'] = $task_content_string[$vs_item['id']]['content'] ?? '';
            }
            $item_arr = $item_list;
        }


        // area_arr 数组的地区 $task_area_json
        $area_arr = [];
        $area_ids = [];
        if (!empty($task_area_json)){
            foreach ($task_area_json as $value){
                if (is_array($value)){
                    foreach ($value as $vs){
                        $area_ids[] = $vs;
                    }
                }else{
                    $area_ids[] = $value;
                }
            }

            $city = CityChinaModel::getUserData([], 'code', $area_ids);
            $city = array_column($city, null, 'code');
            foreach ($task_area_json as $value){
                $temp_arr = [];
                foreach ($value as $vs){
                    unset($temp);
                    $temp['code'] = $vs;
                    $temp['name'] = $city[$vs]['name'] ?? '';
                    $temp_arr[] = $temp;
                }
                $area_arr[] = $temp_arr;
            }
        }

        // 标签 tag_arr
        $tag_arr = $task_tag_json;

        $result = [
            'desc'=> $infoMsg,
            'item_arr'=> $item_arr,
            'area_arr'=> $area_arr,
            'tag_arr'=> $tag_arr
        ];

        return $this->codeSuccess($result);
    }

    public function create_to_user_task(Request $request): object
    {
        $params = $request->only(['id']);

        if (empty($params['id'])) {
            return $this->codeError([], 1011, '参数错误');
        }

        //查询任务
        $userPublic = UserPublicModel::getUserData([], 'id', $params['id']);
        $userPublic = array_column($userPublic, 'user_id');
        $userPublic_count = array_unique($userPublic);
        if (count($userPublic_count) > 1){
            return $this->codeError([], 1011, '只能同时生成一个用户的链接');
        }

        $url_code = md5(time() . adminInfo('id') . $userPublic_count[0] ?? rand(1111,9999));
        ToUserTaskModel::insertSingle([
            'url_code'=> $url_code,
            'ids'=> json_encode($params['id']),
            'created_at'=> time(),
            'op_id'=> adminInfo('id')
        ]);
        $result = [
            'url_code'=> 'http://user.houxiaobao.cn/?url_code=' . $url_code
        ];

        return $this->codeSuccess($result);

    }

    //贡献，引流海报
    public function create_share_image(Request $request): object
    {
        $params = $request->only(['id', 'type']);

        if (empty($params['type'])) {
            return $this->codeError([], 1011, '参数错误');
        }

        if (empty($params['id'])) {
            return $this->codeError([], 1011, '参数错误');
        }

        $public = UserPublicModel::getSingle(['id'=> $params['id']]);
        $title1 = '';

        if($public['share_style'] == 2){
            $title1 = TaskService::getInstance()->handle_rpc_info($params['id']);

        }else{
            if (!empty($public['cat_1'][0]['name'])){
                //获取海报底图
                $title1 = '在侯小报
我创造了'.$public['cat_1'][0]['name'].'信息';
            }
        }

        $share_count = ShareLogModel::getCount();
        $share_count += 1;
        $username = '一路平安
我是第'.$share_count.'位便民信息创造者
长按扫码 跟我一起来创造吧';

        $codeCardUrl = '';
        $image_path = 'storage/oss_img/' . date('Y-m-d', time()) . '/' . time() . '/';
        // 1、先检查文件夹是否存在；2、不存在则新建文件夹
        File::isDirectory($image_path) or File::makeDirectory($image_path, 0777, true, true);
        $image_path = $image_path . rand(10000, 99999) . '.png';

        $image_path_copy = 'storage/oss_img/' . date('Y-m-d', time()) . '/' . time() . '/';
        // 1、先检查文件夹是否存在；2、不存在则新建文件夹
        File::isDirectory($image_path_copy) or File::makeDirectory($image_path_copy, 0777, true, true);
        $image_path_copy = $image_path_copy . rand(10000, 99999) . '.png';

        if ($params['type'] == 2){
            //41引流
            $this->createOp(41, $params['id']);
        }

        $poster = PosterModel::getSingle(['style'=> $params['type']]);
        $poster['image_url'] = explode('http://hxb.apipc.010test.top', $poster['image_url']);

        TaskService::getInstance()->addTextToBackgroundImage($poster['image_url'][1]
            , $title1, $image_path, 'top');

        TaskService::getInstance()->addTextToBackgroundImage($image_path
            , $username, $image_path, 'bottom');

        //默认二维码
        copy('http://hxb.apipc.010test.top/storage/oss_img/2024-03-03/17094696882129/1vgKFUxQQWhDiUQFEA82SzMKZYjY1WReuifu1JYp.png', public_path($image_path_copy));
        TaskService::getInstance()->image_add_image($image_path
            , $image_path_copy
            , $image_path);

        ShareLogModel::insertSingle([
            'url'=> $image_path_copy,
            'op_id'=> adminInfo('id'),
            'created_at'=> time(),
        ]);

        return $this->codeSuccess(['url'=> env('ROUTE_WEB_URL', null) . '/' . $image_path_copy]);
    }

    //站内信消息列表
    public function message_list(Request $request): object
    {
        $params = $request->only(['limit', 'page', 'type']);
        if (empty($params['type'])) {
            return $this->codeError([], 1011, '参数错误');
        }

        $list = MessageModel::getPage(['to_user_id'=> adminInfo('id'), 'deleted_at' => 0, 'type' => $params['type']], $params['limit'] ?? 15);

        //去掉红点
        MessageModel::updateSingle(['to_user_id'=> adminInfo('id'), 'deleted_at' => 0, 'type' => $params['type'], 'is_read'=> 1], [
            'is_read'=> 2
        ]);

        return $this->codeSuccess(FormatBase::listData($list));
    }

    //站内信消息数
    public function message_count(Request $request): object
    {
        $params = $request->only(['type']);
        if (empty($params['type'])) {
            return $this->codeError([], 1011, '参数错误');
        }

        $count = MessageModel::getCount(['to_user_id'=> adminInfo('id'), 'deleted_at' => 0, 'type' => $params['type'], 'is_read'=> 1]);

        return $this->codeSuccess(['count'=>$count]);
    }

    public function update_password(Request $request): object
    {
        $params = $request->only(['password']);
        if (empty($params['password'])) {
            return $this->codeError([], 1011, '参数错误');
        }

        SysUserModel::updateSingle(['id'=> adminInfo('id')], [
            'password' => md5($params['password'])
        ]);

        return $this->codeSuccess();
    }

    //t == 1月初 2月底
    public function handleMonthTime($time, $t){
        $time = strtotime($time);
        $time = date('Y-m', $time);
        if($t == 1){
            $time = strtotime($time);
        }else{
            $time = strtotime("+1 month", strtotime($time));
        }

        return $time;
    }

    public function new_user_statics(Request $request): object
    {
        $params = $request->only(['time']);
        $params['time'] = !empty($params['time']) ? $params['time'] : date('Y-m', time());
        //新用户
        $params['start_time'] = $this->handleMonthTime($params['time'], 1);
        $params['end_time'] = $this->handleMonthTime($params['time'], 2);

        //新用户统计
        $where[] = ['created_at', '>=', $params['start_time'] ];
        $where[] = ['created_at', '<=', $params['end_time'] ];
        $result = UserModel::getUserDataGroup($where);
        $result = array_column($result, null, 'created_date');

        $dateAll = $this->handleTimeDate($params['start_time'], $params['end_time']);
        $line_chart = [];
        foreach ($dateAll as $value){
            if (!empty($result[$value])){
                $line_chart[$value] = $result[$value]['count'];
            }else{
                $line_chart[$value] = 0;
            }
        }
        $where_1 = $where;
        $add_num = UserModel::getCount($where_1);

        $where_1 = [];
        $where_1[] = ['created_at', '>=', $params['start_time'] - (86400 * 30) ];
        $where_1[] = ['created_at', '<=', $params['end_time'] - (86400 * 30)  ];
        $add_rate = UserModel::getCount($where_1);

        if (!empty($add_num)){
            $add_rate = ceil((($add_rate / $add_num) - 1) * 10000) / 100;
        }


        $where_1 = [];
        $where_1[] = ['status', '=', 1 ];
        $order_use_rate = OrderModel::getUserData($where_1, '', [], 0, 'user_id');
        $order_use_rate = count($order_use_rate);

        $where_1 = [];
        $user_use_rate = UserModel::getCount($where_1);

        if (!empty($user_use_rate)){
            $user_use_rate = ceil((($order_use_rate / $user_use_rate)) * 10000) / 100;
        }

        $where_1 = [];
        $where_1[] = ['created_at', '>=', $params['start_time'] - (86400 * 30) ];
        $where_1[] = ['created_at', '<=', $params['end_time'] - (86400 * 30)  ];
        $where_1[] = ['style', '=', 1 ];
        $where_1[] = ['status', '=', 1 ];
        $vip_order_num = OrderModel::getCount($where_1);

        $where_1[] = ['style', '=', 6 ];
        $order_num = OrderModel::getCount($where_1);


        $where_1 = [];
        $where_1[] = ['is_share', '=', 1 ];
        $where_1[] = ['created_at', '>=', $params['start_time'] ];
        $where_1[] = ['created_at', '<=', $params['end_time'] ];
        $public_use_rate = UserPublicModel::getUserData($where_1, '', [], 0, 'user_id','user_id');
        $public_use_rate = count($public_use_rate);

        $where_1 = [];
        $where_1[] = ['created_at', '>=', $params['start_time'] ];
        $where_1[] = ['created_at', '<=', $params['end_time'] ];
        $user_self_rate = UserModel::getCount($where_1);
        if (!empty($user_self_rate)){
            $user_self_rate = ceil((($public_use_rate / $user_self_rate)) * 10000) / 100;

        }

        $where_1 = [];
        $where_1[] = ['created_at', '>=', $params['start_time'] ];
        $where_1[] = ['created_at', '<=', $params['end_time'] ];
        $where_1[] = ['is_share', '=', 1 ];
        $where_1[] = ['share_style', '=', 1 ];
        $self_num_1 = UserPublicModel::getCount($where_1);

        $where_1[] = ['share_style', '=', 2 ];
        $self_num_2 = UserPublicModel::getCount($where_1);

        $where_1 = [];
        $where_1[] = ['info_order.created_at', '>=', $params['start_time'] ];
        $where_1[] = ['info_order.created_at', '<=', $params['end_time'] ];
        $res_1 = OrderModel::query()
            ->selectRaw('t.name, count(1) as count')
            ->join('info_user_public as p', 'p.id', '=', 'info_order.public_id', 'left')
            ->join('info_tags as t', 't.id', '=', 'p.cat_1', 'left')
            ->where(['info_order.style'=> 1])
            ->where($where_1)
            ->groupBy(['cat_1'])
            ->orderBy('count', 'desc')
            ->get()->toArray();

        $res_2 = OrderModel::query()
            ->selectRaw('t.name, count(1) as count')
            ->join('info_user_public as p', 'p.id', '=', 'info_order.public_id', 'left')
            ->join('info_tags as t', 't.id', '=', 'p.cat_1', 'left')
            ->where(['info_order.style'=> 6])
            ->where($where_1)
            ->groupBy(['cat_1'])
            ->orderBy('count', 'desc')
            ->get()->toArray();

        $info = [
            'add_num'=> $add_num,
            'add_rate'=> $add_rate,
            'use_rate'=> $user_use_rate,
            'vip_order_num'=> $vip_order_num,
            'order_num'=>$order_num,
            'vip_order_num_group'=> '5/10/15',
            'self_rate'=> $user_self_rate,
            'self_num'=> $self_num_1 . '/' . $self_num_2,
            'line_chart'=>$line_chart,
            'vip_list'=> $res_1,
            'list'=>$res_2
        ];

        return $this->codeSuccess($info);
    }

    public function user_statics(Request $request): object
    {
        $params = $request->only(['time', 'n']);
        $params['time'] = !empty($params['time']) ? $params['time'] : date('Y-m', time());
        $params['n'] = !empty($params['n']) ? $params['n'] : 0;


        $where_1 = [];
        $where_1[] = ['info_user.created_at', '>=', strtotime($params['time']) ];
        $where_1[] = ['info_user.created_at', '<=', strtotime($params['time']) + (86400 * 30) ];

        $res_1 = UserModel::query()
            ->selectRaw('count(1) as count, sum(if(p.style = 2, 1, 0)) as vip, sum(if(p.style = 2, 0, 1)) as no_vip, sum(if(info_user.number = "", 0, 1)) as name_count')
            ->join('info_user_public as p', 'p.user_id', '=', 'info_user.id', 'left')
            ->whereIn('p.status', [1,2,3,4,5,6,7,1000])
            ->where($where_1)
            ->groupBy(['user_id'])
            ->orderBy('count', 'desc')
            ->get()->toArray();

        $i = 0;
        $j = 0;
        $l = 0;
        foreach ($res_1 as $value){
            if($value['count'] >= $params['n']){
                $i++;
            }
            if($value['vip'] >= $params['n']){
                $j++;
            }
            if($value['no_vip'] >= $params['n']){
                $l++;
            }
        }

        $info = [
            'user_num'=> !empty($res_1[0]['count']) ? $res_1[0]['count'] : 0,
            'use_rate'=> $i,
            'vip_order_rate'=> $j,
            'order_rate'=> $l,
            'name_rate'=> !empty($res_1[0]['name_count']) ? $res_1[0]['name_count'] : 0,
        ];

        return $this->codeSuccess($info);
    }

    public function order_statics(Request $request): object
    {
        $params = $request->only(['start_time', 'end_time']);
        $params['start_time'] = !empty($params['start_time']) ? $params['start_time'] : date('Y-m', time());
        $params['end_time'] = !empty($params['end_time']) ? $params['end_time'] : date('Y-m', time() + 86400);

        $params['start_time'] = $this->handleMonthTime($params['start_time'], 1);
        $params['end_time'] = $this->handleMonthTime($params['end_time'], 2);

        $where[] = ['info_order.created_at', '>=', $params['start_time'] ];
        $where[] = ['info_order.created_at', '<=', $params['end_time'] ];
        $where[] = ['info_order.status', '=', 1 ];
        $result = OrderModel::getUserDataGroup($where);
        $result = array_column($result, null, 'created_date');

        $dateAll = $this->handleTimeDate($params['start_time'], $params['end_time']);
        $line_chart = [];
        foreach ($dateAll as $value){
            if (!empty($result[$value])){
                $line_chart[$value] = $result[$value]['count'];
            }else{
                $line_chart[$value] = 0;
            }
        }

        $where_1 = $where;
        $where_1[] = ['created_at', '>=', $params['start_time'] - (86400 * 30) ];
        $where_1[] = ['created_at', '<=', $params['end_time'] - (86400 * 30)  ];
        $add_num = OrderModel::getCount($where_1);

        $where_1[] = ['style', '=', 1  ];
        $add_num_1 = OrderModel::getCount($where_1);

        $where_1[] = ['style', '=', 6  ];
        $add_num_2 = OrderModel::getCount($where_1);

        $res_3 = OrderModel::query()
            ->selectRaw('p.tag_json,p.is_share, p.share_style, p.status, p.visit_score')
            ->join('info_user_public as p', 'p.id', '=', 'info_order.public_id', 'left')
            ->get()->toArray();
        $res_4 = [];
        $i = 0;
        $j = 0;
        $l = 0;
        $h = 0;
        $a = 0;
        $b = 0;
        $c = 0;
        foreach ($res_3 as $value){
            if (!empty($value['tag_json'])){
                $value['tag_json'] = json_decode($value['tag_json'], true);
                foreach ($value['tag_json'] as $vs){
                    $res_4[] = $vs;
                }
            }

            if(!empty($value['is_share']) && $value['is_share'] == 1){
                $i++;
                if( $value['share_style'] == 1){
                    $j++;
                }else{
                    $l++;
                }
            }

            if(!empty($value['status'] == 1000)){
                $h++;

            }

            if (in_array($value['visit_score'], [1,2])){
                $a++;
            }

            if (in_array($value['visit_score'], [3.4])){
                $b++;

            }

            if (in_array($value['visit_score'], [5])){
                $c++;

            }
        }
        $res_4 = count(array_unique($res_4));

        $where_1 = [];
        $where_1[] = ['info_order.created_at', '>=', $params['start_time'] ];
        $where_1[] = ['info_order.created_at', '<=', $params['end_time'] ];
        $res_1 = OrderModel::query()
            ->selectRaw('t.name, count(1) as count')
            ->join('info_user_public as p', 'p.id', '=', 'info_order.public_id', 'left')
            ->join('info_tags as t', 't.id', '=', 'p.cat_1', 'left')
            ->where(['info_order.style'=> 1])
            ->where($where_1)
            ->groupBy(['cat_1'])
            ->orderBy('count', 'desc')
            ->get()->toArray();

        $res_2 = OrderModel::query()
            ->selectRaw('t.name, count(1) as count')
            ->join('info_user_public as p', 'p.id', '=', 'info_order.public_id', 'left')
            ->join('info_tags as t', 't.id', '=', 'p.cat_1', 'left')
            ->where(['info_order.style'=> 6])
            ->where($where_1)
            ->groupBy(['cat_1'])
            ->orderBy('count', 'desc')
            ->get()->toArray();

        $info = [
            'order_sum_num'=> $add_num,
            'vip_order_num'=> $add_num_1,
            'order_num'=> $add_num_2,
            'reuse_pay_rate'=> 0,
            'order_tag'=> $res_4,
            'self_num'=> $i,
            'self_style_1_num'=> $j,
            'self_style_2_num'=> $l,
            'create_delete'=> $h,
            'like_rate'=> $a . '/' .$b . '/' .$c,
            'line_chart'=>$line_chart,
            'vip_list'=> $res_1,
            'list'=>$res_2
        ];

        return $this->codeSuccess($info);
    }

    public function pay_statics(Request $request): object
    {
        $params = $request->only(['start_time', 'end_time']);
        $params['start_time'] = !empty($params['start_time']) ? $params['start_time'] : date('Y-m', time());
        $params['end_time'] = !empty($params['end_time']) ? $params['end_time'] : date('Y-m', time() + 86400);

        $params['start_time'] = $this->handleMonthTime($params['start_time'], 1);
        $params['end_time'] = $this->handleMonthTime($params['end_time'], 2);

        $where[] = ['info_order.created_at', '>=', $params['start_time'] ];
        $where[] = ['info_order.created_at', '<=', $params['end_time'] ];
        $where[] = ['info_order.status', '=', 1 ];
        $result = OrderModel::getUserDataGroupSum($where);
        $result = array_column($result, null, 'created_date');

        $dateAll = $this->handleTimeDate($params['start_time'], $params['end_time']);
        $line_chart = [];
        foreach ($dateAll as $value){
            if (!empty($result[$value])){
                $line_chart[$value] = $result[$value]['count'] / 100;
            }else{
                $line_chart[$value] = 0;
            }
        }

        $where = [];
        $where[] = ['info_order.created_at', '>=', $params['start_time'] ];
        $where[] = ['info_order.created_at', '<=', $params['end_time'] ];
        $order = OrderModel::query()
            ->selectRaw('info_order.*, p.style')
            ->join('info_user_public as p', 'p.id', '=', 'info_order.public_id', 'left')
            ->where($where)
            ->get()->toArray();

        $pay_sum_money = 0;
        $pay_sum_money_vip = 0;
        $vip_style_1_pay_money = 0;
        $vip_style_2_pay_money = 0;
        $vip_style_3_pay_money = 0;
        $pay_money = 0;
        $unpay_money = 0;
        $bonus_sum = 0;
        foreach ($order as $value){
            if(!(in_array($value['status'], [2,5]))){
                $pay_sum_money += $value['money'] / 100;
            }

            if($value['style'] == 2 && !(in_array($value['status'], [2,5]))){
                $pay_sum_money_vip += $value['money'] / 100;
            }

            if($value['money'] == 500 && !(in_array($value['status'], [2,5]))){
                $vip_style_1_pay_money ++;
            }

            if($value['money'] == 1000 && !(in_array($value['status'], [2,5]))){
                $vip_style_2_pay_money ++;
            }

            if($value['money'] == 1500 && !(in_array($value['status'], [2,5]))){
                $vip_style_3_pay_money ++;
            }

            if($value['style'] == 1 && !(in_array($value['status'], [2,5]))){
                $pay_money += $value['money'] / 100;
            }

            if((in_array($value['status'], [3,4]))){
                $unpay_money += $value['money'] / 100;
            }

        }

        $info = [
            'pay_sum_money'=> $pay_sum_money,
            'vip_pay_money'=> $pay_sum_money_vip,
            'vip_style_1_pay_money'=> $vip_style_1_pay_money,
            'vip_style_2_pay_money'=> $vip_style_2_pay_money,
            'vip_style_3_pay_money'=> $vip_style_3_pay_money,
            'pay_money'=> $pay_money,
            'unpay_money'=> $unpay_money,
            'bonus_sum'=> 0,
            'line_chart'=>$line_chart,
        ];

        return $this->codeSuccess($info);
    }

    public function maintain_statics(Request $request): object
    {
        $params = $request->only(['start_time', 'end_time', 'page', 'limit']);
        $params['start_time'] = !empty($params['start_time']) ? $params['start_time'] : date('Y-m', time());
        $params['end_time'] = !empty($params['end_time']) ? $params['end_time'] : date('Y-m', time() + 86400);
        $params['limit'] = $params['limit'] ?? 15;

        $where = [];

        $whereIn = [];
        $whereIn = ['r.style', [1,3] ];

        $query = SysUserModel::query()
            ->join('info_sys_user_has_roles as ur', 'ur.uid', '=', 'info_sys_users.id', 'left')
            ->join('info_sys_roles as r', 'ur.role_id', '=', 'r.id', 'left');
        $query->where($where);

        if (!empty($whereIn)){
            $query->whereIn($whereIn[0], $whereIn[1]);
        }

        //过滤删选条件-创建时间
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $query->whereBetween('info_sys_users.created_at', [strtotime($params['start_time']), strtotime($params['end_time'])]);
        }

        $list = $query
            ->groupBy('info_sys_users.id')
            ->paginate($params['limit']);

        $list = $list ? $list->toArray() : [];

        foreach ($list['data'] as &$value) {
            $sum_money = OrderModel::query()->where(['user_id'=> $value['id'], 'status' => 1])->get()->toArray();
            $value['sum_money'] = array_sum(array_column($sum_money, 'money'));
            $value['order_sum_num'] = count($sum_money);
            $vip_order_num = OrderModel::query()->where(['user_id'=> $value['id'], 'status' => 1])-> whereIn('style', [1,3,5])->get()->toArray();
            $value['vip_order_num'] = count($vip_order_num);
            $order_num = OrderModel::query()->where(['user_id'=> $value['id'], 'status' => 1])-> whereIn('style', [2,6])->get()->toArray();
            $value['order_num'] = count($order_num);
//            $value['like_rate'] = 0;
//            $value['unpay_money'] = 0;
//            $value['vip_update'] = 0;
//            $value['vip_shift'] = 0;
//            $value['vip_fans'] = 0;
//            $value['vip_match'] = 0;
//            $value['shift'] = 0;
//            $value['match'] = 0;
//            $value['timeout_task'] = 0;
        }

        return $this->codeSuccess(FormatBase::listData($list));
    }

    public function public_statics(Request $request): object
    {
        $params = $request->only(['start_time', 'end_time', 'page', 'limit']);
        $params['start_time'] = !empty($params['start_time']) ? $params['start_time'] : date('Y-m', time());
        $params['end_time'] = !empty($params['end_time']) ? $params['end_time'] : date('Y-m', time() + 86400);
        $params['limit'] = $params['limit'] ?? 15;

        $where = [];

        $whereIn = [];
        $whereIn = ['r.style', [1,2] ];

        $query = SysUserModel::query()
            ->join('info_sys_user_has_roles as ur', 'ur.uid', '=', 'info_sys_users.id', 'left')
            ->join('info_sys_roles as r', 'ur.role_id', '=', 'r.id', 'left');

        $query->where($where);

        if (!empty($whereIn)){
            $query->whereIn($whereIn[0], $whereIn[1]);
        }

        //过滤删选条件-创建时间
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $query->whereBetween('info_sys_users.created_at', [strtotime($params['start_time']), strtotime($params['end_time'])]);
        }
        $list = $query->paginate($params['limit']);

        $list = $list ? $list->toArray() : [];

        foreach ($list['data'] as &$value) {
            $sum_money = OrderModel::query()->where(['user_id'=> $value['id'], 'status' => 1])->get()->toArray();
            $value['already_public_sum'] = count($sum_money);
            $vip_order_num = OrderModel::query()->where(['user_id'=> $value['id'], 'status' => 1])-> whereIn('style', [1,3,5])->get()->toArray();
            $value['vip_already_public'] = count($vip_order_num);
            $already_public = OrderModel::query()->where(['user_id'=> $value['id'], 'status' => 1])-> whereIn('style', [2,6])->get()->toArray();
            $value['already_public'] = count($already_public);
            $unpublic = OrderModel::query()->where(['user_id'=> $value['id']])-> whereIn('style', [2,6])->get()->toArray();
            $value['unpublic'] = count($unpublic);
            $order_num = OrderModel::query()->where(['user_id'=> $value['id']])-> whereIn('status', [2,5])->get()->toArray();
            $value['order_num'] = count($order_num);


//            $value['timeout_public'] = 0;
//            $value['vip_delete'] = 0;
//            $value['delete'] = 0;
        }

        return $this->codeSuccess(FormatBase::listData($list));
    }

    public function task_match_list(Request $request): object
    {
        $params = $request->only(['city_id', 'district_id', 'tag', 'task_id', 'page', 'limit']);
        if (empty($params['task_id'])) {
            return $this->codeError([], 1011, '参数错误');
        }

        //获取任务分类的标签
        $temp = UserPublicModel::query()
            ->with('cat_1_msg')
            ->where(['id'=> $params['task_id']])
            ->first();
        $temp_query_id = !empty($temp['cat_1_msg'][0]['query_id']) ? $temp['cat_1_msg'][0]['query_id'] : 0;

        $params['limit'] = $params['limit'] ?? 15;

        //查询城市和标签
        $where = [];
        $where[] = ['status', '=', 1];
        $whereIn = [];
        $query = UserPublicModel::query();

        if (!empty($temp_query_id)){
            $where[] = ['cat_1', '=', $temp_query_id];
        }

        $query->where($where)
            ->with('admin_msg')
            ->with('cat_1_msg')
            ->with('cat_2_msg')
            ->with('area_msg')
            ->with('city_msg')
            ->with('users')
            ->with('address_msg');;

        $query->whereNotIn('id', [$params['task_id']]);

        if (!empty($params['tag'])) {
            $query->whereJsonContains('tag_json', $params['tag']);

        }

        if(!empty($params['city_id'])){
            $query->whereJsonContains('area_json', [$params['city_id']]);

        }

        if(!empty($params['district_id'])){
            $query->whereJsonContains('area_json', $params['district_id']);

        }

        if (!empty($whereIn)){
            $query->whereIn($whereIn[0], $whereIn[1]);
        }

        $query->orderBy('id', 'desc');

        $list = $query->paginate($params['limit']);

        $list = $list ? $list->toArray() : [];

        $i = 1;
        $user_data = [];
        foreach ($list['data'] as &$value) {
            //分类
            if (!empty($value['cat_2_msg'][0]['name'])){
                $value['cat_2_msg'] = $value['cat_2_msg'][0]['name'];

            }else{
                $value['cat_2_msg'] = '';

            }

            if (!empty($value['cat_1_msg'][0]['que_id'])){
                $value['que_id'] = $value['cat_1_msg'][0]['que_id'];

            }else{
                $value['que_id'] = 0;

            }

            if (!empty($value['cat_1_msg'][0]['name'])){
                $value['cat_1_msg'] = $value['cat_1_msg'][0]['name'];

            }else{
                $value['cat_1_msg'] = '';

            }

            //用户ID
            $value['user_id'] = '';
            if (!empty($value['users'][0]['id'])){
                $value['user_id'] = $value['users'][0]['id'];
            }

            //结束时间
            $value['plain_end_time'] = date('Y-m-d H:i:s', $value['plain_end_time']);

            //创建时间
            $value['created_at'] = date('Y-m-d H:i:s', $value['created_at']);
            //task_message
            $value['task_message'] = TaskService::getInstance()->handle_rpc_info($value['id']);

            //地区
            $area_whole_msg = [];
            if (!empty($value['area_msg'][0]['name'])){
                $area_whole_msg[] = $value['area_msg'][0]['name'];
            }

            if (!empty($value['city_msg'][0]['name'])){
                $area_whole_msg[] = $value['city_msg'][0]['name'];
            }

            if (!empty($value['address_msg'][0]['name'])){
                $area_whole_msg[] = $value['address_msg'][0]['name'];
            }

            if (!empty($area_whole_msg)){
                $value['area_whole_msg'] = implode('-', $area_whole_msg);

            }else{
                $value['area_whole_msg'] = '';
            }

            if (!empty($value['tag_json'])){
                $value['tag_json'] = implode(',', json_decode($value['tag_json'], true));
            }else{
                $value['tag_json'] = '';
            }

            $value['already_public_sum'] = 0;
            $value['vip_already_public'] = 0;
            $value['already_public'] = 0;
            $value['unpublic'] = 0;
            $value['order_num'] = 0;
            $value['timeout_public'] = 0;
            $value['vip_delete'] = 0;
            $value['delete'] = 0;
            if($i <= 5){
                $user_data[] = $value['user_id'];
            }

            unset($value['admin_msg'], $value['area_msg'], $value['city_msg'], $value['users'], $value['address_msg']);
        }
        $logs_id = $this->createOp(42, $params['task_id'], '', $user_data);
        $result = FormatBase::listData($list);
        $result['logs_id'] = $logs_id;

        return $this->codeSuccess($result);
    }

    public function task_match_42(Request $request): object
    {
        $params = $request->only(['logs_id', 'user_id']);
        if (empty($params['logs_id']) || empty($params['user_id'])) {
            return $this->codeError([], 1011, '参数错误');
        }

        $log_info = OpLogsModel::getSingle(['id'=> $params['logs_id']]);
        if(empty($log_info)){
            return $this->codeError([], 1011, '日志不存在');
        }

        $data = [];
        if (!empty($log_info['content'])){
            $data = json_decode($log_info['content'], true);
        }

        foreach ($params['user_id'] as $vsl){
            $data[] = intval($vsl);
        }

        $data = array_unique($data);

        //修改
        OpLogsModel::updateSingle(['id'=> $params['logs_id']], [
            'content'=> json_encode($data)
        ]);

        return $this->codeSuccess();
    }


    //admin_record_detail
    public function admin_record_detail(Request $request):?object
    {
        $params = $request->all(['filling_id']);
        $bool = $this->handleIsNull($params, ['filling_id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        $result = CurlBasiceService::getInstance()->httpPost('http://api.customer.form.bailingkeji.com/admin/record/detail'
            , json_encode([
                'filling_id'=> $params['filling_id']
            ]), []);

        //查询任务
        $filling_info = UserPublicModel::getSingle(['rpc_id'=> $params['filling_id']]);

        if ($result['code'] == 0 && !empty($result['data'])){
            //填充数据
            if(!empty($filling_info)){
                $temp_result_data = [];
                $temp_result_data[] = $this->handle_full($filling_info, $params, 'create_lxr_name', '联系人称呼', 99999999);
                $temp_result_data[] = $this->handle_full($filling_info, $params, 'create_lxr_mobile', '联系电话', 99999998);
                $temp_result_data[] = $this->handle_full($filling_info, $params, 'create_title', '标题', 99999997);
                $temp_result_data[] = $this->handle_full($filling_info, $params, 'plain_end_time', '计划结束时间', 99999994);


                $temp_result_data_end = [];
                $temp_result_data_end[] = $this->handle_full($filling_info, $params, 'area_json', '地区', 99999996);
                $temp_result_data_end[] = $this->handle_full($filling_info, $params, 'tag_json', '标签', 99999995);

                $result['data']['record'] = array_merge($temp_result_data, $result['data']['record'], $temp_result_data_end);
            }
        }

        return response()->json($result);


    }

    //admin_record_detail
    public function admin_record_update(Request $request):?object
    {
        $params = $request->all(['question_info', 'record_id', 'user_id']);
        $bool = $this->handleIsNull($params, ['question_info']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        $temp_update = [];
        $temp_data = [];
        foreach ($params['question_info'] as $value){
            if (!empty($value['bank_id']) && in_array($value['bank_id'], [99999999, 99999998, 99999997, 99999996, 99999995, 99999994])){
                switch ($value['bank_id']){
                    case 99999999:
                        $temp_update['create_lxr_name'] = $value['content'];
                        break;
                    case 99999998:
                        $temp_update['create_lxr_mobile'] = $value['content'];
                        break;
                    case 99999997:
                        $temp_update['create_title'] = $value['content'];
                        break;
                    case 99999995:
                        $temp_update['tag_json'] = json_encode($value['content']);
                        break;
                    case 99999994:
                        $temp_update['plain_end_time'] = strtotime($value['content']);
                        break;
                }
            }else{
                $temp_data[] = $value;
            }
        }
        //修改
        if (!empty($temp_update)){
            UserPublicModel::updateSingle(['rpc_id'=> $params['record_id']], $temp_update);
        }

        $params['question_info'] = $temp_data;
        $result = CurlBasiceService::getInstance()->httpPost('http://api.gz.muke.bailingkeji.com/admin/record/update'
            , json_encode([
                'question_info'=> $params['question_info'],
                'record_id'=> $params['record_id'],
                'user_id'=> $params['user_id'],
            ]), []);
        return response()->json($result);

    }

    public function admin_questionnaire_clone_detail(Request $request):?object
    {
        $params = $request->all(['id', 'task_id']);
        $bool = $this->handleIsNull($params, ['id', 'task_id']);

        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        $result = CurlBasiceService::getInstance()->httpPost('http://api.customer.form.bailingkeji.com/admin/questionnaire/clone/detail'
            , json_encode([
                'id'=> $params['id']
            ]), []);

        $filling_info = UserPublicModel::getSingle(['id'=> $params['task_id']]);

        if ($result['code'] == 0 && !empty($result['data'])){
            //填充数据
            $temp_result_data = [];
            $temp_result_data[] = $this->handle_full_add($filling_info, $params, 'create_lxr_name', '联系人称呼', 99999999);
            $temp_result_data[] = $this->handle_full_add($filling_info, $params, 'create_lxr_mobile', '联系电话', 99999998);
            $temp_result_data[] = $this->handle_full_add($filling_info, $params, 'create_title', '标题', 99999997);
            $temp_result_data[] = $this->handle_full_add($filling_info, $params, 'plain_end_time', '计划结束时间', 99999994);

            $temp_result_data_end = [];
            $temp_result_data_end[] = $this->handle_full_add($filling_info, $params, 'area_json', '地区', 99999996);
            $temp_result_data_end[] = $this->handle_full_add($filling_info, $params, 'tag_json', '标签', 99999995);

            $result['data']['question_info'] = array_merge($temp_result_data, $result['data']['question_info'], $temp_result_data_end);
        }

        return response()->json($result);

    }

    public function admin_record_add(Request $request):?object
    {
        $params = $request->all(['clone_que_id', 'question_info', 'user_id', 'task_id']);
        $bool = $this->handleIsNull($params, ['clone_que_id', 'question_info', 'user_id', 'task_id']);
        if (!$bool){
            return $this->codeError([], 1011, '参数错误');
        }

        $temp_update = [];
        $temp_data = [];
        foreach ($params['question_info'] as $value){
            if (!empty($value['bank_id']) && in_array($value['bank_id'], [99999999, 99999998, 99999997, 99999996, 99999995, 99999994])){
                switch ($value['bank_id']){
                    case 99999999:
                        $temp_update['create_lxr_name'] = $value['content'];
                        break;
                    case 99999998:
                        $temp_update['create_lxr_mobile'] = $value['content'];
                        break;
                    case 99999997:
                        $temp_update['create_title'] = $value['content'];
                        break;
//                    case 99999996:
//                        $temp_update['area_json'] = json_encode($value['content']);
//                        break;
                    case 99999995:
                        $temp_update['tag_json'] = json_encode($value['content']);
                        break;
                    case 99999994:
                        $temp_update['plain_end_time'] = strtotime($value['content']);
                        break;
                }
            }else{
                $temp_data[] = $value;
            }

        }

        $params['question_info'] = $temp_data;
        $result = CurlBasiceService::getInstance()->httpPost('http://api.customer.form.bailingkeji.com/admin/record/add'
            , json_encode([
                'clone_que_id'=> $params['clone_que_id'],
                'question_info'=> $params['question_info'],
                'user_id'=> $params['user_id'],
            ]), []);

        //修改
        if(!empty($result['data']['ins_id'])){
            $temp_update['rpc_id'] = $result['data']['ins_id'];
        }

        if (!empty($temp_update)){
            UserPublicModel::updateSingle(['id'=> $params['task_id']], $temp_update);
        }

        return response()->json($result);

    }

    public function handle_full_add($filling_info, $params, $content, $name, $id)
    {
        $temp_result_data_son['clone_bank_id'] = $id;
        $temp_result_data_son['clone_que_id'] = $id;
        $temp_result_data_son['create_user_id'] = $id;
        $temp_result_data_son['created_at'] = 1709446108;
        $temp_result_data_son['file'] = [];
        $temp_result_data_son['id'] = $id;
        $temp_result_data_son['is_del'] = 2;
        $temp_result_data_son['obj_id'] = $id;
        $temp_result_data_son['option_id'] = [];
        $temp_result_data_son['option_info'] = [];
        $temp_result_data_son['que_type'] = 2;
        $temp_result_data_son['questionnaire_question_id'] = $id;
        $temp_result_data_son['updated_at'] = 1709446108;
        $temp_result_data_son['name'] = $name;


        switch ($content){
            case 'area_json':
            case 'tag_json':
                $type = $id;
                break;
            case 'plain_end_time':
                $type = 4;
                $temp_result_data_son['check_type'] = 1;
                $temp_result_data_son['source_type'] = 1;
                $temp_result_data_son['alias'] = 20;
                $temp_result_data_son['check_number_type'] = 1;
                $temp_result_data_son['check_date'] = 2;
                $temp_result_data_son['check_file_type'] = 1;
                $temp_result_data_son['is_show'] = 1;
                $temp_result_data_son['is_must'] = 1;
                break;
            default:
                $type = 1;
                break;
        }

        $temp_result_data_son['type'] = $type;
        switch ($content){
            case 'area_json':
                $temp_result_data_son['content'] = [];
                if (!empty($filling_info[$content])){
                    $filling_info[$content] = json_decode($filling_info[$content], true);
                    $citu_ids = [];
                    if (!empty($filling_info[$content]) && is_array($filling_info[$content])){
                        foreach ($filling_info[$content] as $vs_1){
                            foreach ($vs_1 as $vs_2){
                                $citu_ids[] = $vs_2;
                            }
                        }

                        $city_all = CityChinaModel::getUserData([], 'code', $citu_ids);
                        $city_all = array_column($city_all, null,'code');

                        foreach ($filling_info[$content] as $vs_1){
                            $public_city = [];
                            foreach ($vs_1 as $vs_2){
                                if (!empty($city_all[$vs_2]['name'])){
                                    $public_city[] = $city_all[$vs_2]['name'];
                                }
                            }
                            $temp_result_data_son['content'][] = $public_city;
                        }
                    }else{
                        $temp_result_data_son['content'] = [];
                    }
                }

                break;
            case 'tag_json':
                $temp_result_data_son['content'] = json_decode($filling_info[$content], true);
                break;
            default:
                $temp_result_data_son['content'] = $filling_info[$content];

                break;
        }
        return $temp_result_data_son;
    }


    public function handle_full($filling_info, $params, $content, $name, $id)
    {
        $temp_result_data_son['clone_bank_id'] = $id;
        $temp_result_data_son['clone_que_id'] = $id;
        switch ($content){
            case 'area_json':
                $temp_result_data_son['content'] = [];
                if (!empty($filling_info[$content])){
                    $filling_info[$content] = json_decode($filling_info[$content], true);
                    $citu_ids = [];
                    if (!empty($filling_info[$content]) && is_array($filling_info[$content])){
                        foreach ($filling_info[$content] as $vs_1){
                            foreach ($vs_1 as $vs_2){
                                $citu_ids[] = $vs_2;
                            }
                        }

                        $city_all = CityChinaModel::getUserData([], 'code', $citu_ids);
                        $city_all = array_column($city_all, null,'code');

                        foreach ($filling_info[$content] as $vs_1){
                            $public_city = [];
                            foreach ($vs_1 as $vs_2){
                                if (!empty($city_all[$vs_2]['name'])){
                                    $public_city[] = $city_all[$vs_2]['name'];
                                }
                            }
                            $temp_result_data_son['content'][] = $public_city;
                        }
                    }else{
                        $temp_result_data_son['content'] = [];
                    }
                }

                break;
            case 'tag_json':
                $temp_result_data_son['content'] = json_decode($filling_info[$content], true);
                break;
            case 'plain_end_time':
                $temp_result_data_son['content'] = date('Y-m-d', $filling_info[$content]);
                break;
            default:
                $temp_result_data_son['content'] = $filling_info[$content];

                break;
        }
        $temp_result_data_son['create_user_id'] = $id;
        $temp_result_data_son['created_at'] = 1709446108;
        $temp_result_data_son['file'] = [];
        $temp_result_data_son['filling_id'] = $params['filling_id'];
        $temp_result_data_son['id'] = $id;
        $temp_result_data_son['is_del'] = 2;
        $temp_result_data_son['obj_id'] = $id;
        $temp_result_data_son['option_id'] = [];
        $temp_result_data_son['option_info'] = [];
        $temp_result_data_son['que_type'] = 2;
        $temp_result_data_son['questionnaire_question_id'] = $id;
        $temp_result_data_son['updated_at'] = 1709446108;
        $temp_result_data_son['bank_info']['alias'] = 1;
        $temp_result_data_son['bank_info']['check_date'] = 1;
        $temp_result_data_son['bank_info']['check_file_type'] = 1;
        $temp_result_data_son['bank_info']['check_number_begin'] = null;
        $temp_result_data_son['bank_info']['check_number_end'] = null;
        $temp_result_data_son['bank_info']['check_number_length'] = 1;
        $temp_result_data_son['bank_info']['check_number_type'] = 1;
        $temp_result_data_son['bank_info']['check_string_end'] = 14;
        $temp_result_data_son['bank_info']['check_string_length'] = 9;
        $temp_result_data_son['bank_info']['check_type'] = 2;
        $temp_result_data_son['bank_info']['name'] = $name ;
        $temp_result_data_son['bank_info']['obj_id'] = $id;
        $temp_result_data_son['bank_info']['number'] = 4;
        $temp_result_data_son['bank_info']['show_type'] = '问答题';
        $temp_result_data_son['bank_info']['sort'] = 0;
        $temp_result_data_son['bank_info']['source_id'] = $id;
        switch ($content){
            case 'area_json':
            case 'tag_json':
                $type = $id;
                break;
            case 'plain_end_time':
                $type = 4;
                $temp_result_data_son['bank_info']['check_type'] = 1;
                $temp_result_data_son['bank_info']['source_type'] = 1;
                $temp_result_data_son['bank_info']['alias'] = 20;
                $temp_result_data_son['bank_info']['check_number_type'] = 1;
                $temp_result_data_son['bank_info']['check_date'] = 2;
                $temp_result_data_son['bank_info']['check_file_type'] = 1;
                $temp_result_data_son['bank_info']['is_show'] = 1;
                $temp_result_data_son['bank_info']['is_must'] = 1;
                break;
            default:
                $type = 1;
                break;
        }
        $temp_result_data_son['bank_info']['type'] = $type;
        $temp_result_data_son['bank_info']['uid'] = 0;
        $temp_result_data_son['bank_info']['updated_at'] = 1709446108;
        $temp_result_data_son['bank_info']['url'] = null;
        return $temp_result_data_son;
    }

    /**
     * 信息类型列表
     * @param Request $request
     * @return object|null
     */
    public function get_tag(Request $request): ?object
    {
        $params = $request->only(['type','title','is_tree','cat_1']);

        $where = [];
        if (!(!empty($params['type']) && $params['type'] == 'all')){
            $where[] = ['parent_id', '=', 0];
        }

        if (!empty($params['title'])){
            $where[] = ['name', 'like', '%' . $params['title'] . '%'];
        }

        if (!empty($params['cat_1'])){
            unset($where);
            $where[] = ['parent_id_path', '=', $params['cat_1']];
        }

        $res = TagsModel::getUserDataCopy($where, '', [], 1, 'id, name, parent_id');

        if (!empty($params['is_tree']) && $params['is_tree'] == 2){
            $res = makeTree($res, 'id', 'parent_id');
        }

        $result = [];
        foreach ($res as $value){
            unset($temp_c);
            $temp_c['id'] = $value['id'];
            $temp_c['name'] = $value['name'];
            $temp_c['parent_id'] = $value['parent_id'];
            $temp_c['_child'] = [];
            if (!empty($value['_child'])){
                $temp_c_c = [];
                foreach ($value['_child'] as $vs){
                    if (!empty($vs['_child'])){
                        foreach ($vs['_child'] as $vs_c){
                            $temp_c_c[] = $vs_c;
                        }
                    }
                }
                $temp_c['_child'] = $temp_c_c;
            }
            $result[] = $temp_c;
        }

        return $this->codeSuccess($result);
    }

    public function search_callback(Request $request): ?object
    {
        $params = $request->only(['seach_three_id','type','time','end_msg']);

        if (empty($params['seach_three_id'])){
            return $this->codeError([], 1011, 'seach_three_id 参数错误');
        }

        if (empty($params['type'])){
            return $this->codeError([], 1011, 'type 参数错误');
        }

        if($params['type'] == 1){
            //消耗1次
            SearchLogModel::insertSingle([
                'search_id'=> $params['seach_three_id'],
                'created_at'=> time()
            ]);

        }else{
            //已结束
            OrderModel::updateSingle(['three_id'=> $params['seach_three_id']], [
                'is_seach_end'=> 1
            ]);
        }

        return $this->codeSuccess();
    }

}
